/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TaskManager2ndEditionView.java
 *
 * Created on Dec 17, 2011, 9:03:15 PM
 */
package taskmanager2ndedition.GUI;

import com.imagine.component.calendar.events.CalendarEvent;
import java.awt.event.WindowEvent;
import javax.swing.JOptionPane;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import taskmanager2ndedition.ClientUserInfo;
import com.imagine.component.calendar.*;
import com.imagine.component.calendar.data.CalendarMonthType;
import com.imagine.component.calendar.events.CalendarEventDateSelectedByMouse;
import java.awt.event.WindowListener;
import javax.swing.table.DefaultTableModel;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimerTask;
import java.util.Vector;
import taskmanager2ndedition.ClientTaskInfo;
import taskmanager2ndedition.StatisticInfo;
import taskmanager2ndedition.Task;
import taskmanager2ndedition.TaskInfo;
import taskmanager2ndedition.client.ClientController;

/**
 *
 * @author Pavel
 */
public class TaskManager2ndEditionView extends javax.swing.JFrame implements CalendarComponentListener, WindowListener {

    private ClientController controller;
    private boolean newTask = true;
    private boolean dateSelected = false;

    private class UpdateTableTask extends TimerTask {

        @Override
        public void run() {
                updateTasks(false);
                updateUsers(false);
        }
    }

    /** Creates new form TaskManager2ndEditionView */
    public TaskManager2ndEditionView(ClientController controller) {
        initComponents();
        this.controller = controller;

        calendarComponent.addCalendarComponentListener(this);
        if (!controller.isAdmin()) {
            addUserButton.setVisible(false);
            deleteUserButton.setVisible(false);
            showForButton.setVisible(false);
            jSeparator1.setVisible(false);
            jSeparator2.setVisible(false);
            jSeparator3.setVisible(false);
            usersListComboBox.removeAllItems();
            usersListComboBox.addItem(controller.getUserLogin());
            usersListComboBox.setEnabled(false);
        } else {
            TableColumnModel columnModel = taskTable.getColumnModel();
            //TableColumn column1 = columnModel.getColumn(0);
            //TableColumn column2 = columnModel.getColumn(1);
            TableColumn column3 = columnModel.getColumn(2);
            //column1.setMaxWidth(250);
            //column1.setPreferredWidth(50);
            //column2.setMaxWidth(250);
            //column2.setPreferredWidth(50);
            column3.setMaxWidth(250);
            column3.setPreferredWidth(150);
        }
        clearInput();

        java.util.Timer timer = new java.util.Timer();
        timer.scheduleAtFixedRate(new UpdateTableTask(), new Date(), controller.getCheckPeriod());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtClosed = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtRemaining = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        taskTable = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        spinMinutes = new javax.swing.JSpinner();
        jScrollPane2 = new javax.swing.JScrollPane();
        taskDescriptionField = new javax.swing.JTextPane();
        spinHours = new javax.swing.JSpinner();
        taskNameField = new javax.swing.JTextField();
        calendarDate = new com.imagine.component.calendar.CalendarComboBox();
        jScrollPane3 = new javax.swing.JScrollPane();
        taskContactsField = new javax.swing.JTextPane();
        addNewTaskButton = new javax.swing.JButton();
        removeTaskButton = new javax.swing.JButton();
        saveTaskButton = new javax.swing.JButton();
        closeTaskButton = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        calendarComponent = new com.imagine.component.calendar.CalendarComponent();
        jToolBar1 = new javax.swing.JToolBar();
        logoutButton = new javax.swing.JButton();
        changePasswordButton = new javax.swing.JButton();
        showAllButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        addUserButton = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        deleteUserButton = new javax.swing.JButton();
        jSeparator4 = new javax.swing.JToolBar.Separator();
        showForButton = new javax.swing.JButton();
        usersListComboBox = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(taskmanager2ndedition.client.TaskManager2ndEditionApp.class).getContext().getResourceMap(TaskManager2ndEditionView.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jPanel1.border.title"), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("jPanel1.border.titleFont"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        txtClosed.setEditable(false);
        txtClosed.setText(resourceMap.getString("txtClosed.text")); // NOI18N
        txtClosed.setToolTipText(resourceMap.getString("txtClosed.toolTipText")); // NOI18N
        txtClosed.setName("txtClosed"); // NOI18N

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        txtRemaining.setEditable(false);
        txtRemaining.setText(resourceMap.getString("txtRemaining.text")); // NOI18N
        txtRemaining.setToolTipText(resourceMap.getString("txtRemaining.toolTipText")); // NOI18N
        txtRemaining.setName("txtRemaining"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(35, 35, 35)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtRemaining, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE)
                    .addComponent(txtClosed, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE))
                .addGap(44, 44, 44))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(55, 55, 55)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtClosed, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtRemaining, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(95, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jPanel2.border.title"), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("jPanel2.border.titleFont"))); // NOI18N
        jPanel2.setName("jPanel2"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        taskTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null}
            },
            new String [] {
                "TaskID", "UserID", "User", "Task", "Due Date", "Status"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        taskTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        taskTable.setColumnSelectionAllowed(true);
        taskTable.setName("taskTable"); // NOI18N
        taskTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        taskTable.getTableHeader().setReorderingAllowed(false);
        taskTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                taskTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(taskTable);
        taskTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        taskTable.getColumnModel().getColumn(0).setMinWidth(0);
        taskTable.getColumnModel().getColumn(0).setPreferredWidth(0);
        taskTable.getColumnModel().getColumn(0).setMaxWidth(0);
        taskTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("taskTable.columnModel.title0")); // NOI18N
        taskTable.getColumnModel().getColumn(1).setMinWidth(0);
        taskTable.getColumnModel().getColumn(1).setPreferredWidth(0);
        taskTable.getColumnModel().getColumn(1).setMaxWidth(0);
        taskTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("taskTable.columnModel.title5")); // NOI18N
        taskTable.getColumnModel().getColumn(2).setMinWidth(50);
        taskTable.getColumnModel().getColumn(2).setPreferredWidth(100);
        taskTable.getColumnModel().getColumn(2).setMaxWidth(300);
        taskTable.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("taskTable.columnModel.title1")); // NOI18N
        taskTable.getColumnModel().getColumn(3).setMinWidth(30);
        taskTable.getColumnModel().getColumn(3).setPreferredWidth(100);
        taskTable.getColumnModel().getColumn(3).setMaxWidth(300);
        taskTable.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("taskTable.columnModel.title2")); // NOI18N
        taskTable.getColumnModel().getColumn(4).setMinWidth(30);
        taskTable.getColumnModel().getColumn(4).setPreferredWidth(80);
        taskTable.getColumnModel().getColumn(4).setMaxWidth(500);
        taskTable.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("taskTable.columnModel.title3")); // NOI18N
        taskTable.getColumnModel().getColumn(5).setMinWidth(30);
        taskTable.getColumnModel().getColumn(5).setPreferredWidth(50);
        taskTable.getColumnModel().getColumn(5).setMaxWidth(250);
        taskTable.getColumnModel().getColumn(5).setHeaderValue(resourceMap.getString("taskTable.columnModel.title4")); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 515, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jPanel3.border.title"), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("jPanel3.border.titleFont"))); // NOI18N
        jPanel3.setName("jPanel3"); // NOI18N

        spinMinutes.setModel(new javax.swing.SpinnerNumberModel(0, 0, 59, 1));
        spinMinutes.setToolTipText(resourceMap.getString("spinMinutes.toolTipText")); // NOI18N
        spinMinutes.setEditor(new javax.swing.JSpinner.NumberEditor(spinMinutes, ""));
        spinMinutes.setName("spinMinutes"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        taskDescriptionField.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("taskDescriptionField.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("taskDescriptionField.border.titleFont"))); // NOI18N
        taskDescriptionField.setToolTipText(resourceMap.getString("taskDescriptionField.toolTipText")); // NOI18N
        taskDescriptionField.setName("taskDescriptionField"); // NOI18N
        jScrollPane2.setViewportView(taskDescriptionField);

        spinHours.setModel(new javax.swing.SpinnerNumberModel(0, 0, 23, 1));
        spinHours.setToolTipText(resourceMap.getString("spinHours.toolTipText")); // NOI18N
        spinHours.setEditor(new javax.swing.JSpinner.NumberEditor(spinHours, ""));
        spinHours.setName("spinHours"); // NOI18N

        taskNameField.setToolTipText(resourceMap.getString("taskNameField.toolTipText")); // NOI18N
        taskNameField.setName("taskNameField"); // NOI18N

        calendarDate.setToolTipText(resourceMap.getString("calendarDate.toolTipText")); // NOI18N
        calendarDate.setName("calendarDate"); // NOI18N

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        taskContactsField.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("taskContactsField.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("taskContactsField.border.titleFont"))); // NOI18N
        taskContactsField.setToolTipText(resourceMap.getString("taskContactsField.toolTipText")); // NOI18N
        taskContactsField.setName("taskContactsField"); // NOI18N
        jScrollPane3.setViewportView(taskContactsField);

        addNewTaskButton.setIcon(resourceMap.getIcon("addNewTaskButton.icon")); // NOI18N
        addNewTaskButton.setText(resourceMap.getString("addNewTaskButton.text")); // NOI18N
        addNewTaskButton.setToolTipText(resourceMap.getString("addNewTaskButton.toolTipText")); // NOI18N
        addNewTaskButton.setName("addNewTaskButton"); // NOI18N
        addNewTaskButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addNewTaskButtonActionPerformed(evt);
            }
        });

        removeTaskButton.setIcon(resourceMap.getIcon("removeTaskButton.icon")); // NOI18N
        removeTaskButton.setText(resourceMap.getString("removeTaskButton.text")); // NOI18N
        removeTaskButton.setToolTipText(resourceMap.getString("removeTaskButton.toolTipText")); // NOI18N
        removeTaskButton.setName("removeTaskButton"); // NOI18N
        removeTaskButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeTaskButtonActionPerformed(evt);
            }
        });

        saveTaskButton.setIcon(resourceMap.getIcon("saveTaskButton.icon")); // NOI18N
        saveTaskButton.setText(resourceMap.getString("saveTaskButton.text")); // NOI18N
        saveTaskButton.setToolTipText(resourceMap.getString("saveTaskButton.toolTipText")); // NOI18N
        saveTaskButton.setName("saveTaskButton"); // NOI18N
        saveTaskButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveTaskButtonActionPerformed(evt);
            }
        });

        closeTaskButton.setIcon(resourceMap.getIcon("closeTaskButton.icon")); // NOI18N
        closeTaskButton.setText(resourceMap.getString("closeTaskButton.text")); // NOI18N
        closeTaskButton.setToolTipText(resourceMap.getString("closeTaskButton.toolTipText")); // NOI18N
        closeTaskButton.setName("closeTaskButton"); // NOI18N
        closeTaskButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeTaskButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(closeTaskButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(removeTaskButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(saveTaskButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(addNewTaskButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
                    .addComponent(taskNameField, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addComponent(calendarDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(spinHours, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(spinMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(addNewTaskButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(removeTaskButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(saveTaskButton, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(closeTaskButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(spinMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(spinHours, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(calendarDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(taskNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(11, 11, 11)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE))))
                .addContainerGap())
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jPanel4.border.title"), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("jPanel4.border.titleFont"))); // NOI18N
        jPanel4.setName("jPanel4"); // NOI18N

        calendarComponent.setName("calendarComponent"); // NOI18N

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(calendarComponent, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(calendarComponent, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
                .addContainerGap())
        );

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setName("jToolBar1"); // NOI18N

        logoutButton.setIcon(resourceMap.getIcon("logoutButton.icon")); // NOI18N
        logoutButton.setText(resourceMap.getString("logoutButton.text")); // NOI18N
        logoutButton.setToolTipText(resourceMap.getString("logoutButton.toolTipText")); // NOI18N
        logoutButton.setFocusable(false);
        logoutButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        logoutButton.setName("logoutButton"); // NOI18N
        logoutButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        logoutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logoutButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(logoutButton);

        changePasswordButton.setIcon(resourceMap.getIcon("changePasswordButton.icon")); // NOI18N
        changePasswordButton.setText(resourceMap.getString("changePasswordButton.text")); // NOI18N
        changePasswordButton.setToolTipText(resourceMap.getString("changePasswordButton.toolTipText")); // NOI18N
        changePasswordButton.setFocusable(false);
        changePasswordButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        changePasswordButton.setName("changePasswordButton"); // NOI18N
        changePasswordButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        changePasswordButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changePasswordButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(changePasswordButton);

        showAllButton.setIcon(resourceMap.getIcon("showAllButton.icon")); // NOI18N
        showAllButton.setText(resourceMap.getString("showAllButton.text")); // NOI18N
        showAllButton.setToolTipText(resourceMap.getString("showAllButton.toolTipText")); // NOI18N
        showAllButton.setFocusable(false);
        showAllButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        showAllButton.setName("showAllButton"); // NOI18N
        showAllButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        showAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showAllButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(showAllButton);

        jSeparator1.setName("jSeparator1"); // NOI18N
        jToolBar1.add(jSeparator1);

        jSeparator2.setName("jSeparator2"); // NOI18N
        jToolBar1.add(jSeparator2);

        addUserButton.setText(resourceMap.getString("addUserButton.text")); // NOI18N
        addUserButton.setFocusable(false);
        addUserButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        addUserButton.setName("addUserButton"); // NOI18N
        addUserButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        addUserButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addUserButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(addUserButton);

        jSeparator3.setName("jSeparator3"); // NOI18N
        jToolBar1.add(jSeparator3);

        deleteUserButton.setText(resourceMap.getString("deleteUserButton.text")); // NOI18N
        deleteUserButton.setFocusable(false);
        deleteUserButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        deleteUserButton.setName("deleteUserButton"); // NOI18N
        deleteUserButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        deleteUserButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteUserButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(deleteUserButton);

        jSeparator4.setName("jSeparator4"); // NOI18N
        jToolBar1.add(jSeparator4);

        showForButton.setText(resourceMap.getString("showForButton.text")); // NOI18N
        showForButton.setFocusable(false);
        showForButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        showForButton.setName("showForButton"); // NOI18N
        showForButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        showForButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showForButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(showForButton);

        usersListComboBox.setMaximumRowCount(200);
        usersListComboBox.setToolTipText(resourceMap.getString("usersListComboBox.toolTipText")); // NOI18N
        usersListComboBox.setMaximumSize(new java.awt.Dimension(200, 20));
        usersListComboBox.setMinimumSize(new java.awt.Dimension(200, 20));
        usersListComboBox.setName("usersListComboBox"); // NOI18N
        usersListComboBox.setPreferredSize(new java.awt.Dimension(200, 20));
        jToolBar1.add(usersListComboBox);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 847, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void logoutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logoutButtonActionPerformed
        // TODO add your handling code here:
        Object[] options = {"Yes",
            "No, go back"};
        int n = JOptionPane.showOptionDialog(this,
                "Would you really like to log out?",
                "Log Out",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                options,
                options[0]);
        if (n == 1) {
            return; // go back to main form
        }

        controller.logout();

        setVisible(false);
        dispose();

        LoginForm loginForm = new LoginForm(controller);
        loginForm.setVisible(true);
        loginForm.setLocationRelativeTo(this);
    }//GEN-LAST:event_logoutButtonActionPerformed

    private void changePasswordButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changePasswordButtonActionPerformed
        // TODO add your handling code here:
        newTask = false;

        Object[] options = {"Yes",
            "No, go back"};
        int n = JOptionPane.showOptionDialog(this,
                "Would you really like to change your password?",
                "Change Password",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                options,
                options[0]);

        if (n == 1) {
            return;
        }

        ChangePasswordForm changeForm = new ChangePasswordForm(controller);
        changeForm.setVisible(true);
        changeForm.setAlwaysOnTop(true);
        changeForm.setLocationRelativeTo(this);
    }//GEN-LAST:event_changePasswordButtonActionPerformed

    private void addNewTaskButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addNewTaskButtonActionPerformed
        // TODO add your handling code here:
        clearInput();
        dateSelected = false;
        newTask = true;
    }//GEN-LAST:event_addNewTaskButtonActionPerformed

    private void addUserButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addUserButtonActionPerformed
        // TODO add your handling code here:
        newTask = false;

        Object[] options = {"Yes",
            "No, go back"};
        int n = JOptionPane.showOptionDialog(this,
                "Would you really like to register a new user?",
                "New User",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                options,
                options[0]);

        if (n == 1) {
            return;
        }
        AddUserForm regForm = new AddUserForm(controller);
        regForm.setVisible(true);
        regForm.setAlwaysOnTop(true);
        regForm.setLocationRelativeTo(this);
        regForm.addWindowListener(this);
    }//GEN-LAST:event_addUserButtonActionPerformed

    private void deleteUserButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteUserButtonActionPerformed
        // TODO add your handling code here:
        newTask = false;

        Object[] options = {"Yes",
            "No, go back"};
        int n = JOptionPane.showOptionDialog(this,
                "Would you really like to delete this user?",
                "Delete User",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                options,
                options[0]);
        if (n == 1) {
            return;
        }

        int a = usersListComboBox.getSelectedIndex();
        if (a < 0) {
            return;
        }
        int id = (Integer) taskTable.getValueAt(a, 1);
        controller.deleteUser(id);
        updateTasks(true);
        updateUsers(true);
    }//GEN-LAST:event_deleteUserButtonActionPerformed

    private void taskTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_taskTableMouseClicked
        // TODO add your handling code here:
        newTask = false;
        int a = taskTable.getSelectedRow();
        if (a < 0) {
            return;
        }
        int id = (Integer) taskTable.getValueAt(a, 0);

        ClientTaskInfo task = controller.findTaskById(id);

        Calendar theDate = new GregorianCalendar();
        theDate.setTime(task.getExpirationDate());

        taskNameField.setText(task.getName());
        taskDescriptionField.setText(task.getDescription());
        taskContactsField.setText(task.getContacts());

        calendarDate.setDate(theDate.getTime());
        spinHours.setValue(theDate.get(Calendar.HOUR_OF_DAY));
        spinMinutes.setValue(theDate.get(Calendar.MINUTE + 2));
    }//GEN-LAST:event_taskTableMouseClicked

    private void showAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showAllButtonActionPerformed
        // TODO add your handling code here:
        newTask = false;
        dateSelected = false;
        updateTasks(true);
    }//GEN-LAST:event_showAllButtonActionPerformed

    private void showForButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showForButtonActionPerformed
        // TODO add your handling code here:
        newTask = false;
        dateSelected = false;

        List<ClientUserInfo> users = controller.getUsers();
        String login = usersListComboBox.getSelectedItem().toString();
        for (ClientUserInfo userForShow : users) {
            if (userForShow.getLogin().equals(login)) {
                controller.setUserId(userForShow.getId());
            }
        }
        updateTasks(true);
    }//GEN-LAST:event_showForButtonActionPerformed

    private void removeTaskButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeTaskButtonActionPerformed
        // TODO add your handling code here:
        newTask = false;

        int a = taskTable.getSelectedRow();
        if (a < 0) {
            return;
        }
        int id = (Integer) taskTable.getValueAt(a, 0);
        ClientTaskInfo task = controller.findTaskById(id);
        if (task != null) {
            controller.removeTask(task);
        }

        clearInput();
        updateTasks(true);
    }//GEN-LAST:event_removeTaskButtonActionPerformed

    private void saveTaskButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveTaskButtonActionPerformed
        // TODO add your handling code here:
        Calendar theDate = new GregorianCalendar();
        theDate.setTime(calendarDate.getDate());
        theDate.set(Calendar.HOUR_OF_DAY, (Integer) spinHours.getValue());
        theDate.set(Calendar.MINUTE, (Integer) spinMinutes.getValue());
        theDate.set(Calendar.SECOND, 0);
        theDate.set(Calendar.MILLISECOND, 0);
        
        if (!controller.validateDate(theDate.getTime())) {
            controller.showErrorMessage("Put a date after now!");
            return;
        }

        if (newTask) {
            ClientTaskInfo task = new Task(
                    taskNameField.getText(),
                    taskDescriptionField.getText(),
                    taskContactsField.getText(),
                    theDate.getTime());
            controller.addTask(task);
        } else {
            int a = taskTable.getSelectedRow();
            if (a < 0) {
                return;
            }

            int id = (Integer) taskTable.getValueAt(a, 0);
            Task task = (Task) controller.findTaskById(id);

            if (task == null) {
                controller.showErrorMessage("Task not found!");
                return;
            }

            task.setName(taskNameField.getText());
            task.setDescription(taskDescriptionField.getText());
            task.setContacts(taskContactsField.getText());
            task.setExpirationDate(new java.util.Date(theDate.getTime().getTime()));
            controller.editTask(task);
        }

        updateTasks(true);
        clearInput();
        newTask = false;
    }//GEN-LAST:event_saveTaskButtonActionPerformed

    private void closeTaskButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeTaskButtonActionPerformed
        // TODO add your handling code here:
        newTask = false;

        int a = taskTable.getSelectedRow();
        if (a < 0) {
            return;
        }
        int id = (Integer) taskTable.getValueAt(a, 0);
        controller.closeTask(id);
        updateTasks(true);
    }//GEN-LAST:event_closeTaskButtonActionPerformed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addNewTaskButton;
    private javax.swing.JButton addUserButton;
    private com.imagine.component.calendar.CalendarComponent calendarComponent;
    private com.imagine.component.calendar.CalendarComboBox calendarDate;
    private javax.swing.JButton changePasswordButton;
    private javax.swing.JButton closeTaskButton;
    private javax.swing.JButton deleteUserButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JToolBar.Separator jSeparator4;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JButton logoutButton;
    private javax.swing.JButton removeTaskButton;
    private javax.swing.JButton saveTaskButton;
    private javax.swing.JButton showAllButton;
    private javax.swing.JButton showForButton;
    private javax.swing.JSpinner spinHours;
    private javax.swing.JSpinner spinMinutes;
    private javax.swing.JTextPane taskContactsField;
    private javax.swing.JTextPane taskDescriptionField;
    private javax.swing.JTextField taskNameField;
    private javax.swing.JTable taskTable;
    private javax.swing.JTextField txtClosed;
    private javax.swing.JTextField txtRemaining;
    private javax.swing.JComboBox usersListComboBox;
    // End of variables declaration//GEN-END:variables

    public Class[] getEventsListened() {
        Class[] a = new Class[1];
        a[0] = new CalendarEventDateSelectedByMouse(calendarComponent, CalendarMonthType.NEXT_MONTH, null).getClass();
        return a;
    }

    public void processCalendarEvent(CalendarEvent ce) {
        if (ce instanceof CalendarEventDateSelectedByMouse) {
            newTask = false;
            updateTasksTableOnDate();
        }
    }

    private void updateStatistics() {
        StatisticInfo info = controller.updateStatistics();
        txtClosed.setText(((Integer) info.nClosed).toString());
        txtRemaining.setText(((Integer) info.nOpened).toString());
    }

    private void updateTaskTable() {
        DefaultTableModel model1 = (DefaultTableModel) taskTable.getModel();
        List<ClientTaskInfo> list = controller.getTasks();
        controller.setTaskListModified(false);
        model1.setRowCount(0);
        for (int i=0; i < list.size(); i++) {
            Vector rowData = new Vector();
            rowData.add(list.get(i).getId());
            rowData.add(list.get(i).getUserId());
            rowData.add(list.get(i).getUserId());
            rowData.add(list.get(i).getName());
            rowData.add(list.get(i).getExpirationDate());
            rowData.add(list.get(i).getStatus().toString());
            model1.addRow(rowData);
            taskTable.setModel(model1);
        }
    }

    private void updateTasksTableOnDate() {
        DefaultTableModel model1 = (DefaultTableModel) taskTable.getModel();
        List<ClientTaskInfo> tasksOnDate = controller.getTasksOnDate(new java.util.Date(calendarComponent.getDate().getTime()));
        model1.setRowCount(0);
        for (TaskInfo task : tasksOnDate) {
            Vector rowData = new Vector();            
            rowData.add(task.getId());
            rowData.add(task.getUserId());
            rowData.add(task.getUserId());
            rowData.add(task.getName());
            rowData.add(task.getExpirationDate());
            rowData.add(task.getStatus().toString());
            model1.addRow(rowData);
            taskTable.setModel(model1);
        }
    }

    private void updateTasks(boolean force) {
        if (force){
            controller.forceUpdateTasks();
        }
        if (!controller.isTaskListModified()){
            return;
        }
        if (dateSelected) {
            updateTasksTableOnDate();
        } else {
            updateTaskTable();
        }
        updateStatistics();
    }

    private void clearInput() {
        taskNameField.setText("");
        taskDescriptionField.setText("");
        taskContactsField.setText("");

        Calendar now = new GregorianCalendar();
        calendarDate.setDate(now.getTime());
        spinHours.setValue(now.get(Calendar.HOUR_OF_DAY));
        spinMinutes.setValue(now.get(Calendar.MINUTE) + 2);
    }

    private void updateUsers(boolean force) {
        if (!controller.isAdmin()) {
            return;
        }
        if (force){
            controller.forceUpdateUsers();
        }
        if (!controller.isUserListModified()){
            return;
        }
        String selection = "";
        if (usersListComboBox.getSelectedIndex() >= 0){
            selection = usersListComboBox.getSelectedItem().toString();
        }
        usersListComboBox.removeAllItems();
        List<ClientUserInfo> updateUsers = controller.getUsers();
        controller.setUserListModified(false);
        int nSelected = 0;
        for (int i=0; i < updateUsers.size(); i++) {
            usersListComboBox.addItem(updateUsers.get(i).getLogin());
            if (updateUsers.get(i).getLogin().equals(selection))
                nSelected = i;
        }
        usersListComboBox.setSelectedIndex(nSelected);
        usersListComboBox.setEnabled(true);
    }

    public void windowOpened(WindowEvent e) {
    }

    public void windowClosing(WindowEvent e) {
    }

    public void windowClosed(WindowEvent e) {
        updateTasks(true);
        updateUsers(true);
    }

    public void windowIconified(WindowEvent e) {
    }

    public void windowDeiconified(WindowEvent e) {
    }

    public void windowActivated(WindowEvent e) {
    }

    public void windowDeactivated(WindowEvent e) {
    }
}
